package com.colortea.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.colortea.action.backstage.utils.BaseTools;
import com.colortea.action.backstage.utils.enums.BaseEnums.DataUsingState;
import com.colortea.action.backstage.utils.enums.BaseEnums.LogisticsShowRange;
import com.colortea.action.backstage.utils.enums.BaseEnums.OrderIsInvoice;
import com.colortea.action.backstage.utils.enums.BaseEnums.OrderPayState;
import com.colortea.action.backstage.utils.enums.BaseEnums.OrderShippingState;
import com.colortea.action.backstage.utils.enums.BaseEnums.OrderState;
import com.colortea.action.backstage.utils.statickey.StaticKey;
import com.colortea.action.frontstage.order.OrderObj;
import com.colortea.action.frontstage.utils.Arith;
import com.colortea.action.frontstage.utils.PaymentCode;
import com.colortea.action.frontstage.utils.enums.FrontEnums.CartGoodsState;
import com.colortea.action.frontstage.utils.enums.FrontEnums.ShippingAddressIssend;
import com.colortea.action.frontstage.utils.enums.FrontEnums.ShippingAddressStatus;
import com.colortea.dao.CartTDao;
import com.colortea.dao.DeliverAddressTDao;
import com.colortea.dao.GoodsTDao;
import com.colortea.dao.LogisticsBAreaTDao;
import com.colortea.dao.LogisticsBTDao;
import com.colortea.dao.MemberInvoiceTDao;
import com.colortea.dao.OrderInvoiceTDao;
import com.colortea.dao.OrderTDao;
import com.colortea.dao.PaymentMDao;
import com.colortea.dao.ShippingAddressTDao;
import com.colortea.entity.CartT;
import com.colortea.entity.DeliverAddressT;
import com.colortea.entity.GoodsT;
import com.colortea.entity.LogisticsBusinessT;
import com.colortea.entity.LogisticsbusinessareaT;
import com.colortea.entity.MemberInvoiceT;
import com.colortea.entity.MemberT;
import com.colortea.entity.OrderInvoiceT;
import com.colortea.entity.OrderT;
import com.colortea.entity.PaymentM;
import com.colortea.entity.ShippingAddressT;
import com.colortea.service.OrderBaseProcessTService;

@Service("orderBaseProcessTService")
@Scope("prototype")
public class OrderBaseProcessTServiceImpl implements OrderBaseProcessTService {
	@Resource
	private Serial serial;
	@Resource
	private DeliverAddressTDao deliverAddressTDao;
	@Resource
	private LogisticsBTDao logisticsBTDao;
	@Resource
	private PaymentMDao paymentMDao;
	@Resource
	private CartTDao cartTDao;
	@Resource
	private LogisticsBAreaTDao logisticsBAreaTDao;
	@Resource
	private OrderTDao orderTDao;
	@Resource
	private ShippingAddressTDao shippingAddressTDao;
	@Resource
	private MemberInvoiceTDao memberInvoiceTDao;
	@Resource
	private GoodsTDao goodsTDao;
	@Resource
	private OrderInvoiceTDao orderInvoiceTDao;

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public List<DeliverAddressT> getMemberDeliverAddress(MemberT m) {
		Criterion criterion = Restrictions.eq("memberid", m.getId());
		return deliverAddressTDao.findByCriteria(DeliverAddressT.class,
				criterion);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public List<LogisticsBusinessT> getLogisticstsBusiness(String state) {
		Criterion criterion = Restrictions.eq("state",
				LogisticsShowRange.FRONTSTAGE.getState());
		return logisticsBTDao.findByCriteria(LogisticsBusinessT.class,
				criterion);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public List<PaymentM> getPaymentM(String state) {
		Criterion criterion = Restrictions.eq("state",
				DataUsingState.USING.getState());
		return paymentMDao.findByCriteria(PaymentM.class, criterion);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public List<CartT> getMemberCart(String memberid, String state,
			String orderTag) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("memberid", memberid);
		params.put("state", state);
		params.put("orderTag", orderTag);
		Criterion criterion = Restrictions.allEq(params);
		return cartTDao.findByCriteria(CartT.class, criterion);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public List<LogisticsBusinessT> getDefaultLogisticsBusinessT(String visible) {
		Criterion criterion = Restrictions.eq("visible", visible);
		return logisticsBTDao.findByCriteria(LogisticsBusinessT.class,
				criterion);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public List<LogisticsbusinessareaT> getDefaultLogisticsbusinessareaT(
			String logisticsid) {
		Criterion criterion = Restrictions.eq("logisticsid", logisticsid);
		return logisticsBAreaTDao.findByCriteria(LogisticsbusinessareaT.class,
				criterion);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public PaymentM getSelectedPayMent(String paymentid) {
		return paymentMDao.findByPK(PaymentM.class, paymentid);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public DeliverAddressT getDeliverAddress(String addressid) {
		return deliverAddressTDao.findByPK(DeliverAddressT.class, addressid);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public OrderT getOrder(String orderid) {
		return orderTDao.findByPK(OrderT.class, orderid);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public ShippingAddressT getShippingAddress(String deliveraddressid,
			String state, String orderid) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("deliveraddressid", deliveraddressid);
		params.put("state", state);
		params.put("orderid", orderid);
		Criterion criterion = Restrictions.allEq(params);
		return shippingAddressTDao.findOneByCriteria(ShippingAddressT.class,
				criterion);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public List<ShippingAddressT> getShippingAddress(String orderid) {
		Criterion criterion = Restrictions.eq("orderid", orderid);
		return shippingAddressTDao.findByCriteria(ShippingAddressT.class,
				criterion);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public List<MemberInvoiceT> getMyInvoice(String memberid) {
		Criterion criterion = Restrictions.eq("memberid", memberid);
		return memberInvoiceTDao
				.findByCriteria(MemberInvoiceT.class, criterion);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public OrderObj saveFrontOrder(String deliveraddressid, String paymentid,
			String cartgoodsid, String logisticsid, String freight,
			String customernotes, String isgoodsfromcart, String ordertag,
			String invoiceid, MemberT mt, String defaultbank) {
		OrderObj o = new OrderObj();
		// 获取本次订单id
		String orderid = this.serial.Serialid(Serial.ORDER);
		// 订单名称由购物车商品名称组合
		String ordername = "";
		// 订单中商品信息id串
		String orderproductinfoid = "";
		// 订单主图
		String orderpicture = "";
		// 订单中所有商品数量
		int needquantity = 0;
		// 订单价格不包含运费
		double amount = 0.0;

		DeliverAddressT da = this.deliverAddressTDao.findByPK(
				DeliverAddressT.class, deliveraddressid);
		// 获取支付方式
		PaymentM pm = getSelectedPayMent(paymentid);
		if (pm != null && da != null) {
			// 添加发货地址信息
			ShippingAddressT s = new ShippingAddressT();
			s.setShippingaddressid(this.serial.Serialid(Serial.SHIPPINGADDRESS));
			s.setMemberid(da.getMemberid());
			s.setShippingusername(da.getShippingusername());
			s.setCountry(da.getCountry());
			s.setProvince(da.getProvince());
			s.setCity(da.getCity());
			s.setDistrict(da.getDistrict());
			s.setStreet(da.getStreet());
			s.setPostcode(da.getPostcode());
			s.setTelno(da.getTelno());
			s.setMobile(da.getMobile());
			s.setEmail(da.getEmail());
			s.setCreatetime(BaseTools.getSystemTime());
			s.setState(ShippingAddressStatus.BINDEDORDER.getState());
			s.setDeliveraddressid(da.getAddressid());
			s.setIssend(ShippingAddressIssend.UNSEND.getState());// 未发送到这个地址过
			s.setOrderid(orderid);// 设置订单号
			this.shippingAddressTDao.save(s);

			if (StringUtils.equalsIgnoreCase(PaymentCode.PAYMENT_CODE_ALIPAY,
					pm.getPaymentCode())) {
				o.setPaycode(PaymentCode.PAYMENT_CODE_ALIPAY);
			} else if (StringUtils.equalsIgnoreCase(
					PaymentCode.PAYMENT_CODE_TENPAY, pm.getPaymentCode())) {
				o.setPaycode(PaymentCode.PAYMENT_CODE_TENPAY);
			} else if (StringUtils.equalsIgnoreCase(
					PaymentCode.PAYMENT_CODE_BALANCEPAY, pm.getPaymentCode())) {
				o.setPaycode(PaymentCode.PAYMENT_CODE_BALANCEPAY);
			} else if (StringUtils.equalsIgnoreCase(
					PaymentCode.E_CURRENCY_PAYMENT, pm.getPaymentCode())) {
				o.setPaycode(PaymentCode.E_CURRENCY_PAYMENT);
				o.setDefaultbank(defaultbank);
			}else {
				o.setPaycode(PaymentCode.PAYMENT_CODE_DELIVERYPAY);
			}

			// 增加订单
			// 生成一个同批次购物车号
			String ids[] = StringUtils.split(cartgoodsid,
					StaticKey.SPLITDOT);
			int idslength=ids.length;
			if (idslength>1) {
				String cartid = this.serial.Serialid(Serial.CART);
				Map<String, String> params = new HashMap<String, String>();
				for (String ss : ids) {
					params.put("goodsid", ss);
					params.put("memberid", mt.getId());
					params.put("state",
							CartGoodsState.NEWADDTOCART_NUM.getState());
					Criterion criterion = Restrictions.allEq(params);
					CartT ct = this.cartTDao.findOneByCriteria(CartT.class,
							criterion);
					ct.setOrderid(orderid);
					ct.setCartid(cartid);
					ct.setState(CartGoodsState.HAVEVENORDER.getState());
					this.cartTDao.update(ct);
					params.clear();
					orderproductinfoid += ct.getGoodsid() + StaticKey.SPLITDOT;
					ordername += ct.getGoodsname();
					orderpicture = ct.getPicture();
					needquantity += ct.getNeedquantity();
					amount += Arith.mul(ct.getFavorable().doubleValue(),
							ct.getNeedquantity());
				}
			} else {
				GoodsT gt = this.goodsTDao.findByPK(GoodsT.class, ids[0]);
				orderproductinfoid = ids[0];
				//GoodsT gt = this.goodsTDao.findByPK(GoodsT.class, cartgoodsid);
				//orderproductinfoid = cartgoodsid;
				String cartid = this.serial.Serialid(Serial.CART);
				Map<String, String> params = new HashMap<String, String>();
				params.put("goodsid", ids[0]);
				params.put("memberid", mt.getId());
				params.put("state",
						CartGoodsState.NEWADDTOCART_NUM.getState());
				Criterion criterion = Restrictions.allEq(params);
				
				CartT ct = this.cartTDao.findOneByCriteria(CartT.class,
						criterion);
				if (ct!=null) {
					ct.setOrderid(orderid);
					ct.setCartid(cartid);
					ct.setState(CartGoodsState.HAVEVENORDER.getState());
					this.cartTDao.update(ct);
				}
				params.clear();
				ordername = gt.getGoodsname();
				String pcs[] = StringUtils.split(gt.getPictureurl(),
						StaticKey.SPLITDOT);
				if (pcs != null && pcs.length > 0) {
					orderpicture = pcs[0];
				}
				needquantity = 1;
				amount = gt.getMemberprice().doubleValue();
			}

			// 创建订单
			OrderT order = new OrderT();
			order.setOrderid(orderid);
			order.setUserid(StaticKey.EMPTY);
			order.setUsername(StaticKey.EMPTY);
			order.setMemberid(mt.getId());
			order.setMembername(mt.getLoginname());
			order.setDelivermode(StaticKey.DELIVERMODE_EXPRESS);
			order.setDeliverynumber(StaticKey.EMPTY);
			order.setOrderstate(OrderState.ORDERSTATE_CONFIRMED_ONE_NUM
					.getState());// 已确认
			order.setPaystate(OrderPayState.ORDERPAYSTATE_UNPAY_ZERO_NUM
					.getState());// 未付款
			order.setShippingstate(OrderShippingState.ORDERSHIPPINGSTATE_UNDELIVER_GOODS_ZERO_NUM
					.getState());// 未发货
			order.setLogisticsid(logisticsid);
			order.setLogisticswebaddress(StaticKey.EMPTY);
			order.setProductinfo(orderproductinfoid);
			order.setOrdername(ordername);
			order.setMainpicture(orderpicture);
			order.setNeedquantity(needquantity);
			order.setFreight(Double.parseDouble(freight));
			order.setAmount(amount);
			order.setPurchasetime(BaseTools.getSystemTime());
			order.setDeliverytime(null);
			order.setDeliverynumber(StaticKey.EMPTY);
			order.setIsinvoice(OrderIsInvoice.ORDERISINVOICE_UNDO_ZERO_NUM
					.getState());
			order.setCustomerordernotes(customernotes);
			order.setPaytime(null);
			order.setOrderTag(ordertag);
			order.setToBuyerNotes(StaticKey.EMPTY);
			order.setShouldpay(Arith.add(amount, Double.parseDouble(freight)));
			order.setUsepoints(0.0);
			order.setVouchersid(StaticKey.EMPTY);
			order.setCreatetime(BaseTools.getSystemTime());
			order.setUpdatetime(BaseTools.getSystemTime());
			order.setIsprintexpress(StaticKey.EXPRESS_NOT_PRINT_ZERO_NUM);// 未打印快递单
			order.setIsprintinvoice(StaticKey.INVOICE_NOT_PRINT_ZERO_NUM);// 未打印发货单
			order.setIsprintfpinvoice(StaticKey.PINVOICE_NOT_PRINT_ZERO_NUM);// 未开具发票
			order.setExpressnumber(StaticKey.EMPTY);// 快递单号
			order.setPaymentid(paymentid);
			order.setPaymentname(pm.getPaymentname());
			order.setShippingaddressid(s.getShippingaddressid());// 设置发货地址到订单中
			order.setDeliveraddressid(da.getAddressid());// 设置收货地址到订单中
			order.setShippingusername(da.getShippingusername());// 设置收货人
			if("wyzf".equals(pm.getPaymentCode()) || pm.getPaymentCode() == "wyzf"){
				order.setDefaultbank(defaultbank);// 银行简码				
			}
			this.orderTDao.save(order);

			// 保存订单开票信息
			MemberInvoiceT mi=memberInvoiceTDao.findByPK(MemberInvoiceT.class, invoiceid);
			if(mi!=null){
				OrderInvoiceT oi=new OrderInvoiceT();
				oi.setOrderInvoiceid(this.serial.Serialid(Serial.ORDERINVOICE));
				oi.setAmount(String.valueOf(order.getShouldpay()));
				oi.setCreatetime(BaseTools.getSystemTime());
				oi.setInvContent(order.getOrdername());
				oi.setInvPayee(mi.getInvpayee());
				oi.setInvType(mi.getInvpayee());
				oi.setMemberid(mi.getMemberid());
				oi.setMembername(mt.getLoginname());
				oi.setOrderid(orderid);
				oi.setShopid(StaticKey.EMPTY);
				oi.setState(OrderIsInvoice.ORDERISINVOICE_UNDO_ZERO_NUM.getState());
				oi.setUpdatetime(BaseTools.getSystemTime());
				oi.setVersiont(1);
				this.orderInvoiceTDao.save(oi);
			}
			o.setOut_trade_no(order.getOrderid()); // 订单号
			o.setSubject(order.getOrdername()); // 商品名称
			o.setTotal_fee(String.valueOf(order.getAmount())); // 金额
			
		}
		return o;
	}

}
